﻿// ------------------------------------------------------------------------------
//  © 2008 OpenUpon™.  All rights reserved.
// ------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Queries;
using NHibernate;
using NHibernate.Expression;
using NHibernate.Transform;

namespace CastUpon.Entities {
	[ActiveRecord]
	public class ListenerLog : ActiveRecordBase<ListenerLog> {
		private string agent;
		private int id;
		private string ipAddress;
		private DateTime logDateTime;
		private string referrer;
		private string uri;

		[PrimaryKey]
		public int Id {
			get { return this.id; }
			set { this.id = value; }
		}

		[Property]
		public string Uri {
			get { return this.uri; }
			set { this.uri = value; }
		}

		[Property]
		public string Agent {
			get { return this.agent; }
			set { this.agent = value; }
		}

		[Property]
		public string Referrer {
			get { return this.referrer; }
			set { this.referrer = value; }
		}

		[Property]
		public DateTime LogDateTime {
			get { return this.logDateTime; }
			set { this.logDateTime = value; }
		}

		[Property]
		public string IpAddress {
			get { return this.ipAddress; }
			set { this.ipAddress = value; }
		}

		public static void AddLogEntry(ListenerLog listenerLogEntry) {
			listenerLogEntry.LogDateTime = DateTime.Now;
			listenerLogEntry.Save();
		}

		public static int NumberOfListeners() {
			//DetachedCriteria detachedCriteria = DetachedCriteria.For(typeof(ListenerLog)).
			//  SetProjection(Projections.ProjectionList()
			//                  .Add(Projections.CountDistinct("IpAddress"))
			//                  //.Add(Projections.GroupProperty("IpAddress"))
			//  );
		//return Count(detachedCriteria);
			string query = @"select count (distinct log.IpAddress)  from ListenerLog log";

			ScalarQuery<int> QueryEscalar = new ScalarQuery<int>(typeof(ListenerLog), QueryLanguage.Hql, query);
			return Convert.ToInt32(ExecuteQuery(QueryEscalar));
		}
	}
}